package com.example.hms.service.serviceImpl;
import com.example.hms.Dao.RoomTypeDao;
import com.example.hms.entity.RoomType;
import com.example.hms.service.RoomTypeService;
import com.example.hms.ulit.Result;
import com.example.hms.ulit.ResultSubmit;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)
public class RoomTypeServiceImpl implements RoomTypeService {
    @Resource
    RoomTypeDao roomTypeDao;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Result selectAllRoomType(String roomTypeName, BigDecimal roomPrice) {
        List<RoomType> rooms = roomTypeDao.selectAllRoomType(roomTypeName, roomPrice);
        return ResultSubmit.success(rooms);
    }

    @Override
    public Result insert(RoomType roomType) {
        roomType.setDataUpdateTime(format.format(new Date()));
        roomType.setRoomTypeId(Math.abs((int)System.currentTimeMillis()));
        roomType.setDeleteIdentity("未删除");
        int insert=roomTypeDao.insert(roomType);
        if(insert==0){
            return ResultSubmit.error("添加失败");

        }else {
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.success("添加成功");
        }
    }

    @Override
    public Result update(RoomType roomType) {
        //    修改传入数据中的基础信息（删除标识、创建时间）
        int update1=roomTypeDao.update(roomType.getRoomTypeId().toString());
        roomType.setDeleteIdentity("未删除");
        roomType.setDataUpdateTime(format.format(new Date()));
        //    清除roomType中的基础信息
        roomType.setRoomTypeId(0);
        int insert1=roomTypeDao.insert(roomType);
        //    todo 系统记录操作
        //    根据删除方法、新增方法返回值判断逻辑修改整个功能是否执行成功
        //    不成功则返回报错并回滚
        if(update1==1 || insert1==1){
            return ResultSubmit.success("修改成功");
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("修改失败");
        }
    }

    @Override
    public Result delete(String roomTypeId) {
        int delete1=roomTypeDao.update(roomTypeId);
        if(delete1==1){
            return ResultSubmit.success("成功");
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("失败");
        }
    }
    }
